package com.nowcoder.community.service;

import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Page;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SearchService {

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    public List<DiscussPost> searchDiscussPost(String keyword, Page page) {
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.multiMatchQuery(keyword, "title", "content"))
                .withHighlightFields(
                        new HighlightBuilder.Field("title").preTags("<em>").postTags("</em>"),
                        new HighlightBuilder.Field("content").preTags("<em>").postTags("</em>")
                ).withPageable(PageRequest.of(page.getCurrent() - 1, page.getLimit(), Sort.by("createTime")))
                .build();
        SearchHits<DiscussPost> searchHits = elasticsearchRestTemplate.search(searchQuery, DiscussPost.class);
        page.setRows(searchHits.getTotalHits());
        List<DiscussPost> discussPosts = new ArrayList<>();
        for (SearchHit<DiscussPost> searchHit : searchHits) {
            discussPosts.add(searchHit.getContent());
            if (!searchHit.getHighlightField("content").isEmpty()) {
                searchHit.getContent().setContent(searchHit.getHighlightField("content").get(0));
            }
            if (!searchHit.getHighlightField("title").isEmpty()) {
                searchHit.getContent().setContent(searchHit.getHighlightField("title").get(0));
            }
        }
        return discussPosts;
    }
}
